<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-card">
        <!-- Logo Section -->
        <div class="logo-section">
          <div class="logo-icon">
            <svg class="logo-symbol" width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect width="20" height="20" rx="2" fill="white"/>
              <path d="M10 2L2 18H18L10 2Z" fill="#2C2C2C"/>
              <circle cx="10" cy="10" r="3" fill="white"/>
            </svg>
          </div>
          <span class="logo-text">AI教育资源平台</span>
        </div>

        <!-- Header Section -->
        <div class="header-section">
          <h1 class="welcome-title">创建账户</h1>
          <p class="welcome-subtitle">加入我们的AI教育平台，开启您的学习之旅</p>
        </div>

        <!-- Registration Form -->
        <form class="login-form" @submit.prevent="handleRegister">
          <!-- Step 1: Basic Info -->
          <div v-if="step === 1">
            <div class="form-group">
              <label class="form-label">用户身份</label>
              <div class="input-wrapper">
                <select
                    v-model="registerForm.role"
                    class="form-select"
                    required
                >
                  <option value="" disabled>请选择您的身份</option>
                  <option value="student">学生</option>
                  <option value="teacher">教师</option>
                </select>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">用户名</label>
              <div class="input-wrapper">
                <input
                    type="text"
                    v-model="registerForm.username"
                    class="form-input"
                    placeholder="请输入用户名"
                    required
                />
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">邮箱</label>
              <div class="input-wrapper">
                <input
                    type="email"
                    v-model="registerForm.email"
                    class="form-input"
                    placeholder="请输入邮箱地址"
                    required
                />
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">密码</label>
              <div class="input-wrapper">
                <input
                    :type="showPassword ? 'text' : 'password'"
                    v-model="registerForm.password"
                    class="form-input"
                    placeholder="请输入密码"
                    required
                />
                <button
                    type="button"
                    class="password-toggle"
                    @click="showPassword = !showPassword"
                >
                  <el-icon style="font-size: 18px;">
                    <component :is="showPassword ? View : Hide" />
                  </el-icon>
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">确认密码</label>
              <div class="input-wrapper">
                <input
                    :type="showConfirmPassword ? 'text' : 'password'"
                    v-model="registerForm.confirmPassword"
                    class="form-input"
                    placeholder="请再次输入密码"
                    required
                />
                <button
                    type="button"
                    class="password-toggle"
                    @click="showConfirmPassword = !showConfirmPassword"
                >
                  <el-icon style="font-size: 18px;">
                    <component :is="showConfirmPassword ? View : Hide" />
                  </el-icon>
                </button>
              </div>
            </div>

            <button type="submit" class="login-button" :disabled="isSending">
              {{ isSending ? '发送验证码中...' : '下一步' }}
            </button>
          </div>

          <!-- Step 2: Email Verification -->
          <div v-else>
            <div class="verification-info">
              <p class="verification-text">我们已向 <strong>{{ registerForm.email }}</strong> 发送了验证码</p>
            </div>

            <div class="form-group">
              <label class="form-label">验证码</label>
              <div class="input-wrapper">
                <input
                    type="text"
                    v-model="verificationCode"
                    class="form-input"
                    placeholder="请输入6位验证码"
                    maxlength="6"
                    required
                />
              </div>
            </div>

            <div class="resend-section">
              <span class="resend-text">没有收到验证码？</span>
              <button
                  type="button"
                  class="resend-button"
                  :disabled="resendCountdown > 0"
                  @click="resendCode"
              >
                {{ resendCountdown > 0 ? `${resendCountdown}s后重发` : '重新发送' }}
              </button>
            </div>

            <button type="submit" class="login-button" :disabled="isVerifying">
              {{ isVerifying ? '验证中...' : '完成注册' }}
            </button>

            <button type="button" class="back-button" @click="step = 1">
              返回上一步
            </button>
          </div>
        </form>

        <!-- Terms Agreement -->
        <div v-if="step === 1" class="terms-agreement">
          <label class="remember-me">
            <input
                type="checkbox"
                v-model="agreeToTerms"
                class="checkbox"
            />
            <span class="checkbox-label">
              我已阅读并同意
              <a href="#" class="terms-link">《服务条款》</a>
              和
              <a href="#" class="terms-link">《隐私政策》</a>
            </span>
          </label>
        </div>

        <!-- Divider -->
        <div class="divider">
          <span class="divider-text">或</span>
        </div>

        <!-- Login Link -->
        <div class="signup-link">
          <span class="signup-text">已有账户？</span>
          <router-link to="/login" class="signup-button">立即登录</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElIcon, ElMessage } from 'element-plus'
import { registerAPI, sendVerificationCodeAPI, verifyCodeAPI } from "@/apis"
import { Hide, View } from "@element-plus/icons-vue"

const router = useRouter()

// 步骤控制
const step = ref(1) // 1: 基本信息, 2: 邮箱验证

// 表单数据
const registerForm = reactive({
  role: '', // 新增用户身份字段
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const verificationCode = ref('')
const agreeToTerms = ref(false)

// 状态控制
const isSending = ref(false)
const isVerifying = ref(false)
const resendCountdown = ref(0)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 定时器
let resendTimer: number | null = null

// 表单验证
const validateForm = () => {
  if (!registerForm.role) {
    ElMessage.warning('请选择您的身份')
    return false
  }
  if (!registerForm.username) {
    ElMessage.warning('请输入用户名')
    return false
  }
  if (registerForm.username.length < 3) {
    ElMessage.warning('用户名长度至少3位')
    return false
  }
  if (!registerForm.email) {
    ElMessage.warning('请输入邮箱')
    return false
  }
  if (!registerForm.password) {
    ElMessage.warning('请输入密码')
    return false
  }
  if (registerForm.password.length < 6) {
    ElMessage.warning('密码长度至少6位')
    return false
  }
  if (!registerForm.confirmPassword) {
    ElMessage.warning('请确认密码')
    return false
  }
  if (registerForm.password !== registerForm.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return false
  }
  if (!agreeToTerms.value) {
    ElMessage.warning('请先同意服务条款和隐私政策')
    return false
  }
  return true
}

// 处理注册
const handleRegister = async () => {
  if (step.value === 1) {
    // 第一步：验证基本信息并发送验证码
    if (!validateForm()) return

    isSending.value = true
    try {
      // 发送验证码
      const res = await sendVerificationCodeAPI(registerForm.email)
      if (res.code !== 200) {
        ElMessage.error(res.message)
        return
      }
      ElMessage.success('验证码已发送，请检查您的邮箱')
      step.value = 2
      startResendCountdown()
    } catch (err) {
      ElMessage.error('发送失败，请稍后重试')
    } finally {
      isSending.value = false
    }
  } else {
    // 第二步：验证验证码并完成注册
    if (!verificationCode.value) {
      ElMessage.warning('请输入验证码')
      return
    }
    if (verificationCode.value.length !== 6) {
      ElMessage.warning('请输入6位验证码')
      return
    }

    isVerifying.value = true
    try {
      // 验证验证码
      const res = await verifyCodeAPI({
        email: registerForm.email,
        verificationCode: verificationCode.value,
      })
      if (res.code !== 200) {
        ElMessage.error(res.message)
        return
      }

      // 调用注册接口，包含role字段
      const regres = await registerAPI({
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password,
        role: registerForm.role // 传递用户选择的身份
      })
      if (regres.code !== 200) {
        ElMessage.error(regres.message)
        return
      }
      ElMessage.success('注册成功！欢迎加入AI教育平台')
      router.push('/login')
    } catch (err) {
      ElMessage.error('验证码错误或注册失败，请重试')
    } finally {
      isVerifying.value = false
    }
  }
}

// 重新发送验证码
const resendCode = async () => {
  if (resendCountdown.value > 0) return

  isSending.value = true
  try {
    const res = await sendVerificationCodeAPI(registerForm.email)
    if (res.code !== 200) {
      ElMessage.error(res.message)
      return
    }
    ElMessage.success('验证码已重新发送')
    startResendCountdown()
  } catch (err) {
    ElMessage.error('发送失败，请稍后重试')
  } finally {
    isSending.value = false
  }
}

// 开始重发倒计时
const startResendCountdown = () => {
  resendCountdown.value = 60
  resendTimer = setInterval(() => {
    resendCountdown.value--
    if (resendCountdown.value <= 0 && resendTimer) {
      clearInterval(resendTimer)
      resendTimer = null
    }
  }, 1000)
}

// 组件卸载时清理定时器
import { onUnmounted } from 'vue'

onUnmounted(() => {
  if (resendTimer) {
    clearInterval(resendTimer)
  }
})
</script>

<style scoped>
.login-page {
  width: 100vw;
  min-height: 100vh;
  background: linear-gradient(90deg, #F8FAFC 0%, #F1F5F9 50%, #E2E8F0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'Inter', sans-serif;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 448px;
}

.login-card {
  background: white;
  border-radius: 8px;
  border: 1px solid #D9D9D9;
  padding: 48px 32px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

/* Logo Section */
.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 32px;
}

.logo-icon {
  width: 40px;
  height: 40px;
  background: #2C2C2C;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-symbol {
  width: 20px;
  height: 20px;
  background: white;
  border-radius: 2px;
}

.logo-text {
  color: #1E1E1E;
  font-size: 24px;
  font-weight: 700;
  line-height: 32px;
}

/* Header Section */
.header-section {
  text-align: center;
  margin-bottom: 40px;
}

.welcome-title {
  color: #1E1E1E;
  font-size: 30px;
  font-weight: 700;
  line-height: 36px;
  margin: 0 0 12px 0;
}

.welcome-subtitle {
  color: #B3B3B3;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  margin: 0;
}

/* Form Styles */
.login-form {
  margin-bottom: 32px;
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  color: #1E1E1E;
  font-size: 14px;
  font-weight: 600;
  line-height: 21px;
  margin-bottom: 8px;
}

.input-wrapper {
  position: relative;
}

.form-input {
  width: 100%;
  height: 49px;
  background: white;
  border: 1px solid #D9D9D9;
  border-radius: 8px;
  padding: 0 16px;
  font-size: 16px;
  font-family: 'Inter', sans-serif;
  color: #1E1E1E;
  box-sizing: border-box;
}

/* 下拉选择框样式 */
.form-select {
  width: 100%;
  height: 49px;
  background: white;
  border: 1px solid #D9D9D9;
  border-radius: 8px;
  padding: 0 16px;
  font-size: 16px;
  font-family: 'Inter', sans-serif;
  color: #1E1E1E;
  box-sizing: border-box;
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6,9 12,15 18,9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 16px center;
  background-size: 16px;
}

.form-select:focus {
  outline: none;
  border-color: #2C2C2C;
  box-shadow: 0 0 0 2px rgba(44, 44, 44, 0.1);
}

.form-select option {
  color: #1E1E1E;
  background: white;
  padding: 8px;
}

.form-input::placeholder {
  color: #999999;
  font-size: 16px;
  font-weight: 400;
}

.form-input:focus {
  outline: none;
  border-color: #2C2C2C;
  box-shadow: 0 0 0 2px rgba(44, 44, 44, 0.1);
}

.password-toggle {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
}

.eye-icon {
  width: 18.33px;
  height: 12.50px;
  background: black;
  border-radius: 2px;
  transition: opacity 0.3s;
}

.eye-icon.eye-closed {
  opacity: 0.5;
}

/* Verification Info */
.verification-info {
  background: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  text-align: center;
}

.verification-text {
  color: #64748B;
  font-size: 14px;
  font-weight: 400;
  line-height: 20px;
  margin: 0;
}

/* Resend Section */
.resend-section {
  text-align: center;
  margin-bottom: 24px;
}

.resend-text {
  color: #B3B3B3;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
  margin-right: 8px;
}

.resend-button {
  background: none;
  border: none;
  color: #2C2C2C;
  font-size: 14px;
  font-weight: 600;
  line-height: 21px;
  cursor: pointer;
  text-decoration: underline;
  padding: 0;
}

.resend-button:disabled {
  color: #B3B3B3;
  cursor: not-allowed;
  text-decoration: none;
}

.resend-button:hover:not(:disabled) {
  color: #1a1a1a;
}

/* Terms Agreement */
.terms-agreement {
  margin-bottom: 24px;
}

.remember-me {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
}

.checkbox {
  width: 16px;
  height: 16px;
  border: 1px solid #D9D9D9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  margin-top: 2px;
  flex-shrink: 0;
}

.checkbox-label {
  color: #1E1E1E;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
}

.terms-link {
  color: #2C2C2C;
  text-decoration: none;
}

.terms-link:hover {
  text-decoration: underline;
}

/* Buttons */
.login-button {
  width: 100%;
  height: 48px;
  background: #2C2C2C;
  border: none;
  border-radius: 8px;
  color: #F5F5F5;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.login-button:hover:not(:disabled) {
  background: #1a1a1a;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(44, 44, 44, 0.3);
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.back-button {
  width: 100%;
  height: 48px;
  background: white;
  border: 1px solid #D9D9D9;
  border-radius: 8px;
  color: #2C2C2C;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #F8FAFC;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Divider */
.divider {
  position: relative;
  text-align: center;
  margin-bottom: 24px;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #D9D9D9;
}

.divider-text {
  background: white;
  color: #B3B3B3;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
  padding: 0 16px;
  position: relative;
  z-index: 1;
}

/* Sign Up Link */
.signup-link {
  text-align: center;
}

.signup-text {
  color: #B3B3B3;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
  margin-right: 8px;
}

.signup-button {
  color: #2C2C2C;
  font-size: 14px;
  font-weight: 600;
  line-height: 21px;
  text-decoration: none;
}

.signup-button:hover {
  text-decoration: underline;
}

/* Responsive Design */
@media (max-width: 768px) {
  .login-page {
    padding: 16px;
  }

  .login-card {
    padding: 32px 24px;
  }
}

@media (max-width: 480px) {
  .welcome-title {
    font-size: 24px;
    line-height: 30px;
  }

  .welcome-subtitle {
    font-size: 14px;
  }

  .logo-text {
    font-size: 20px;
  }
}
</style>